import json

from lxml import etree

from crawler_core.constant.constants import Constants
from crawler_core.constant.constants_api import ConstantAPI
from crawler_core.driver.driver_proxy import DriverProxy
from crawler_core.exception.cookies_exec import CookieException
from crawler_core.exception.unknown_exec import UnknownException
from lib.sys.logger_factory import LoggerFactory
from lib.sys.sys_config import SystemConfig
from login_server.utils.vertify_code_utils import VertifyCodeUtils
from time import sleep
from PIL import Image
from selenium.webdriver import ActionChains
from search_verify_code_server.interface_verify import VerifyInterface
from search_verify_code_server.template.template_51job import Verify51job


class VerifyJob51(VerifyInterface):
    logger = LoggerFactory.getLogger("VerifyJob51", "search")

    def __init__(self):
        pass

    def verify(self, url, cookies):
        self.driver = DriverProxy().get()
        self.cookies = cookies
        try:
            self.unlock(url)
        except CookieException:
            VerifyJob51.logger.info("VerifyJob51 开始解析跳转验证码 cookies 失效...")
            data = {Constants.SEARCH_CODE: ConstantAPI.RETURN_ERROR_COOKIES}
            return data
        except UnknownException as e:
            VerifyJob51.logger.info("VerifyJob51 开始解析跳转验证码 出现未知错误...")
            data = {
                Constants.SEARCH_CODE: ConstantAPI.RETURN_ERROR_UNKNOWN,
                Constants.SEARCH_MSG: json.dumps(e)
            }
            return data
        data = {Constants.SEARCH_CODE: ConstantAPI.RETURN_SUCCESS}
        return data
        pass

    def unlock(self, url):
        driver = self.driver
        cookies = self.cookies
        driver.maximize_window()

        url_start = 'https://ehire.51job.com/Candidate/SearchResumeNew.aspx'
        driver.get(url_start)
        driver.delete_all_cookies()
        for cookie in cookies:
            driver.add_cookie(cookie_dict=cookie)
        driver.get(url)
        sleep(3)
        # 判断是否可以直接验证
        html = etree.HTML(driver.page_source)
        message = "".join(html.xpath('//input[@id="hidShowCode"]/@value'))
        if message != "1":
            VerifyJob51.logger.info("VerifyJob51 搜索失败，cookie失效，帮我重新登录一下-----")
            raise CookieException()
        # 进行截屏的处理
        driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")
        image_path = SystemConfig.get_p_screen_image_path()
        driver.save_screenshot(image_path + '/51job_verify_image.png')
        catch_greest = driver.find_element_by_xpath("//div[@class='yz-main']")
        width = catch_greest.size["width"]
        height = catch_greest.size['height']
        print(width, height)
        point_x = catch_greest.location["x"]
        point_y = catch_greest.location["y"] - Verify51job.position_y
        print(point_x, point_y)
        elementwidth = point_x + catch_greest.size["width"]
        elementheight = point_y + catch_greest.size["height"]
        picture = Image.open(image_path + '/51job_verify_image.png')
        imgFrame = picture.crop((point_x, point_y, elementwidth, elementheight - Verify51job.position_h))
        imgFrame.save(image_path + '/51job_verify_image2.png')
        im = open(image_path + '/51job_verify_image2.png', 'rb').read()
        xy = VertifyCodeUtils.analysis(im, 9004)
        locations = xy["pic_str"].split("|")
        print(locations)
        location_x1, location_y1 = locations[0].split(",")
        x1 = int(location_x1)
        y1 = int(location_y1)
        sleep(1)
        ActionChains(driver).move_to_element_with_offset(catch_greest, xoffset=x1, yoffset=y1).click().perform()
        location_x2, location_y2 = locations[1].split(",")
        x2 = int(location_x2)
        y2 = int(location_y2)
        sleep(1)
        ActionChains(driver).move_to_element_with_offset(catch_greest, xoffset=x2, yoffset=y2).click().perform()
        location_x3, location_y3 = locations[2].split(",")
        x3 = int(location_x3)
        y3 = int(location_y3)
        sleep(1)
        ActionChains(driver).move_to_element_with_offset(catch_greest, xoffset=x3, yoffset=y3).click().perform()
        location_x4, location_y4 = locations[3].split(",")
        x4 = int(location_x4)
        y4 = int(location_y4)
        sleep(1)
        ActionChains(driver).move_to_element_with_offset(catch_greest, xoffset=x4, yoffset=y4).click().perform()
        sleep(1)
        driver.save_screenshot(image_path + '/51job_verify_image3.png')
        driver.find_element_by_xpath('//div[@class="yz-bot-fn"]/a[@id="btnValidate"]').click()
        sleep(3)
        driver.save_screenshot(image_path + '/51job_verify_image4.png')
        driver.close()
        driver.quit()
